// 全局变量
var config = require("./config.js");


// 封装登录,通过code获取token,并保存到缓存
function login() {
	return new Promise((resolve, reject) => {
		// 启动信息
		let {
			path,
			scene,
			query
		} = uni.getLaunchOptionsSync();

		// 只要一些手机信息
		const {
			brand,
			model,
			osName
		} = uni.getSystemInfoSync();
		// 把启动query参数也拼接上去,可以看到是谁邀请的
		let systeminfo = {
			brand,
			model,
			osName,
			query
		};
		systeminfo = JSON.stringify(systeminfo);
		// jsCode
		uni.login({
			success: (res) => {
				uni.request({
					url: config.domain + '/member/login',
					method: 'POST',
					header: {
						'content-type': 'application/x-www-form-urlencoded',
					},
					data: {
						code: res.code,
						scene,
						launchPath: path,
						systeminfo
					},
					success: (result) => {
						if (result.data.code === 2000) {
							// 存储token
							let token = result.data.data.token;
							uni.setStorageSync('token', token);
							// 把请求信息返回
							resolve(result.data);
						} else {
							uni.$u.toast(result.data.message);
							reject('登录失败，请重新进入')
						}
					}
				})
			}
		})
	})
}

// 封装request请求
function request(url, data, method, contentType) {
	return new Promise((resolve, reject) => {
		let access = uni.getStorageSync('access') || '';
		header = {}
		if (access && access != '') {
			header = {
				'Authorization': 'Bearer ' + access
			}
		}
		uni.request({
			url: config.domain + url,
			data: data || {},
			header: header,
			method: method,
			success: (result) => {
				// 网络请求成功
				if (result.statusCode === 200) {
					if (result.data.code === 4001) {
						uni.$u.toast('未授权');
						uni.navigateTo({
							url: '/pages/loginIn/loginIn'
						});
					}
					// 业务通过，返回数据
					resolve(result.data);
				} else {
					uni.$u.toast('网络请求失败，请检查网络是否连通或稍后再试')
					// uni.$u.toast('error，服务器CPU负载过高')
					reject('网络请求失败，请检查网络是否连通或稍后再试');
				}
			},
			fail: (res) => {
				uni.$u.toast('网络请求失败，请检查小程序版本')
				// uni.$u.toast('error，服务器CPU负载过高')
				reject('网络请求失败，请检查小程序版本');
			},
			complete: (res) => {},
		})
	})
}

// 封装post请求
function post(url, data) {
	return request(url, data, 'post', 'application/x-www-form-urlencoded');
}

// 封装get请求
function get(url, data) {
	return request(url, data, 'get');
}


// 暴露
exports.request = request;
exports.post = post;
exports.get = get;
exports.login = login;